/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.grnt.dbcommon;

import org.grnt.dbcommon.DataControler.DataControlException;
import org.grnt.common.*;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * This class is objects' id management center. All Ids managering are integrated
 * into a center . All objects' id in the system are with uniform type Long and
 * auto increamenting meothed for new an Id number.
 * @author sayid
 */

public class IdExtractor {
	/**
	 *
	 * To return a new id number of a correct object.
	 * @param name Represents the id for witch corresponding object.
	 * @return A correct object's new id number.
	 * @throws org.grnt.dbcommon.DataControler.DataControlException
	 */
	public static Long nextId(String name) throws DataControlException{
		IdResult buddyIdEx = new IdResult(name);
		DataControler.query(buddyIdEx);
		return buddyIdEx.getId();
	}

	private static class IdResult implements ResultBean {
		Long id = null;
		final String key;
		final String qryStr = "SELECT gt_buddy_seq_next('?') as ? FROM dual";
		
		public IdResult(String key) {
			this.key = key;
		}

		public String getQueryString() {
			return CommonFunc.sqlStrFormat(qryStr, key, key);
		}
		
		public void fullValues(ResultSet rs) throws FullValuesException{
			try {
				rs.beforeFirst();
				if (rs.next()) {
					id = rs.getLong(key);
				} else {
					id = null;
				}
			} catch (SQLException ex) {
				throw new FullValuesException(ex);
			}
		}
		
		public Long getId() {
			return id;
		}
	}
}
